// axios的配置
import axios from 'axios'
import router from '../router/index'

const isProduction = process.env.NODE_ENV === 'production'
const http = axios.create({
  baseURL: isProduction ? 'http://49.234.121.123' : '/api',
  timeout: 12000
})

// get请求参数拼接
const getUrl = (url, params) => {
  if (JSON.stringify(params) === '{}') return url
  let newUrl = `${url}?`
  Object.keys(params).forEach(key => {
    newUrl += `${key}=${params[key]}&`
  })

  return newUrl.substring(0, newUrl.length - 1)
}
// 请求拦截
http.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      // 判断是否存在token，如果存在的话，则每个http header都加上token
      config.headers.Authorization = token
    }
    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)

// 响应拦截
http.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          router.push('/')
      }
    }
    return Promise.resolve(error.response.data)
  }
)

// 进一步封装request
const request = (method, url, data = {}) => {
  switch (method) {
    case 'get':
      // eslint-disable-next-line no-case-declarations
      const newUrl = getUrl(url, data)
      return http.get(newUrl)
    case 'post':
      return http.post(url, data, {
        headers: {
          'Content-Type': 'application/json'
        }
      })
    default:
      throw new Error('请求方法错误！')
  }
}

// CMJ写法
export default request
